// 用封装后的线程库 实现抢票逻辑

#include <iostream>
#include <string>
#include <unistd.h>
#include <functional>
#include <pthread.h>

namespace ThreadModule
{
    template<typename T>
    using func_t = std::function<void(T)>;
    // using func_t = std::function<void(const T&)>;

    template<typename T>
    class Thread
    {
    public:
        void Excute()
        {
            _func(_data);
        }
    public:
        Thread(func_t<T> func,T data,const std::string& name = "none-name")
            :_func(func), _data(data), _threadname(name), _stop(true)
        {}

        ~Thread()
        {}

        static void* threadroution(void *args)
        {
            Thread<T>* self = static_cast<Thread<T>*>(args);
            self->Excute();
            return nullptr;
        }

        bool Start()
        {
            int n = pthread_create(&_tid, nullptr, threadroution, this);
            if(!n)
            {
                _stop = false;
                return true;
            }
            else
            {
                return false;
            }
        }

        void Detach()
        {
            if(!_stop)
            {
                pthread_detach(_tid);
            }
        }

        void Join()
        {
            if(!_stop)
            {
                pthread_join(_tid, nullptr);
            }
        }

        std::string name()
        {
            return _threadname;
        }

        void Stop()
        {
            _stop = true;
        }
    
    private:
        pthread_t _tid;
        func_t<T> _func;
        T _data;
        std::string _threadname;
        bool _stop;
    };
    
}